package io.codescience.aianaly.controller;

import io.codescience.aianaly.service.DeepseekService;
import io.codescience.aianaly.utils.FileParser;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import io.codescience.aianaly.model.User;

@Controller
public class InterviewController {

    @Autowired
    private DeepseekService deepseekService;

    @GetMapping("/interview")
    public String interviewPage(HttpSession session,Model model) {
        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }

        // 添加当前用户信息到模型
        User user = (User) session.getAttribute("user");
        model.addAttribute("currentUser", user);

        return "interview";
    }

    @PostMapping("/analyze")
    public String analyzeResume(
            @RequestParam("resumeFile") MultipartFile file,
            HttpSession session,
            Model model) {

        // 1. 检查用户是否登录
        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }

        try {
            if (file.isEmpty()) {
                model.addAttribute("error", "请选择要上传的文件");
                return "interview";
            }

            // 解析文件内容
            String resumeText = FileParser.parseFile(file);

            // 调用AI分析
            String analysisResult = deepseekService.analyzeResume(resumeText);

            model.addAttribute("originalText", resumeText);
            model.addAttribute("analysisResult", analysisResult);
            model.addAttribute("fileName", file.getOriginalFilename());
            //添加用户信息到界面
            model.addAttribute("currentUser", session.getAttribute("user"));
            return "result";

        } catch (Exception e) {
            model.addAttribute("error", "文件处理错误: " + e.getMessage());
            return "interview";
        }
    }
}